<?php

/**
* 实现给文章自动添加索引，在文章的最开头列出文章的索引，有利于SEO，只需要在文章中把子标题用<h3>框起来即可
*/

function article_index($content) {
    $matches = array();
		$index_list = '<ul id="article-index">';
    $ul_li = '';
    $r = "/<h3>([^<]+)<\/h3>/im";
    if(preg_match_all($r, $content, $matches)) {
        foreach($matches[1] as $num => $title) {
            $content = str_replace($matches[0][$num], '<h3 id="title-'.$num.'">'.$title.'</h3>', $content);
						$index_list .= '<li><a href="#title-'.$num.'" title="'.$title.'">'.$title."</a></li>\n";
        }
				$index_list .= '</ul>';
				$content = $index_list.$content;
    }
    return $content;
}
add_filter( "the_content", "article_index" );
